const db = wx.cloud.database()
// 搜索的关键字
let keyword = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    modalShow: false,
    count: 10,
    bloglist: [],
    issend: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getBlogList(this.data.bloglist.length)
    db.collection('on-off').get().then((res)=> {
      this.setData({
        issend: res.data[0].tosend
      })
    })
  },
  
  onPublish() {
    //判断用户是否授权
    wx.getSetting({
      success: (res) => {
        // console.log(res)
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) => {
              this.onLoginSuccess({
                detail: res.userInfo
              })
            }
          })
        } else {
          this.setData({
            modalShow: true,
          })
        }
      }
    })
  },
  onLoginSuccess(event) {
    const detail = event.detail
    wx.navigateTo({
      url: `../blog-edit/blog-edit?nickName=${detail.nickName}&avatarUrl=${detail.avatarUrl}`,
    })
  },
  onLoginFail() {
    wx.showModal({
      title: '授权用户才能发布',
      content: '',
      success: ((res)=> {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          this.setData({
            showModal: false
          })
        }
      
      }) 
        
    })
  },
  onSearch(event) {
    // console.log(event.detail.keyword)
    this.setData({
      bloglist: []
    })
    keyword = event.detail.keyword
    this._getBlogList(0)
  },
  //获取blog
  _getBlogList(start) {
    wx.showLoading({
      title: '拼命加载中',
    })
    let w = {}
    if (keyword.trim != '') {
      w = {
        content: new db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      }
    }
    // console.log(w)
    db.collection('blog')
    .where(w)
    .skip(start)
    .limit(this.data.count)
    .orderBy('createTime', 'desc')
    .get().then((res)=> {
      let list = res.data
      for (let i=0; i<list.length; i++) {
        list[i].createTime = list[i].createTime.toString()
      }
      this.setData({
        bloglist: this.data.bloglist.concat(list)
      })
      wx.hideLoading()
      wx.stopPullDownRefresh()
    })
    
  },
  goComment(event) {
    wx.navigateTo({
      url: '../../pages/blog-comment/blog-comment?blogId=' + event.target.dataset.blogid,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      bloglist: []
    })
    this._getBlogList(0)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this._getBlogList(this.data.bloglist.length)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})